package com.company.sum_lists;


/**
 * link: https://leetcode-cn.com/problems/sum-lists-lcci/
 */


public class Solution {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode header = new ListNode(-1);
        ListNode pre = header;
        int temp = 0;
        while (l1 != null || l2 != null) {
            if (pre.val != -1) {
                pre.next = new ListNode(0);
                pre = pre.next;
            }
            int count = 0;
            if (l1 == null) {
                count = l2.val;
            } else if (l2 == null) {
                count = l1.val;
            } else {
                count = l1.val + l2.val;
            }
            count = count + temp;
            int result = count % 10;
            temp = count / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
            pre.val = result;
        }
        if (temp != 0) {
            pre.next = new ListNode(temp);
        }
        return header;
    }

    public ListNode getAList() {
        ListNode a7 = new ListNode(1);
        ListNode a1 = new ListNode(1);
        ListNode a6 = new ListNode(6);
        a1.next = a6;
        a7.next = a1;
        return a7;
    }

    public ListNode getBList() {
        ListNode a7 = new ListNode(9);
        ListNode a1 = new ListNode(9);
        ListNode a6 = new ListNode(2);
        a1.next = a6;
        a7.next = a1;
        return a7;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        // write your code here
        System.out.println(solution.addTwoNumbers(solution.getAList(), solution.getBList()));
    }
}
